#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <cassert>

using namespace std;
//父进程读取，子进程写入
int main(){
    //1、父进程创建管道
    int pipefd[2];
    int n=pipe(pipefd);
    assert(n==0);

    //2、父进程fork出子进程
    pid_t id=fork();
    assert(id>=0);
    if(id==0){
        //子进程
        //子进程进行写入
        close(pipefd[0]);
        int num=0;
        while(1){
            num++;
            string str="Hello,["+to_string(num)+"],["+to_string(getpid())+"]";
            write(pipefd[1],str.c_str(),str.size());
        }
        exit(0);
    }
    //父进程进行读取
    close(pipefd[1]);
    while(1){
        char buffer[1024];
        ssize_t bytesRead = read(pipefd[0], buffer, sizeof(buffer) - 1); // 读取数据
        if (bytesRead > 0) {
            buffer[bytesRead] = '\0'; // 添加字符串结束符
            cout << "Message: " << buffer << " | my pid: " << getpid() << endl;
        } else {
            break; // 如果没有读取到数据，退出循环
        }
        sleep(1);
    }
    n=waitpid(id,NULL,0);
    assert(n==id);
}